package com.ipay.controller;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.servlet.ServletContext;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import com.ipay.redis.JedisConnectionPool;
import net.sf.json.JSONObject;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;
import com.ipay.entity.CashiersEntity;
import com.ipay.entity.MerchantInfoEntity;
import com.ipay.entity.QRCodeEntity;
import com.ipay.service.CashiersService;
import com.ipay.service.MerchantInfoService;
import com.ipay.service.QRCodeService;
import com.ipay.service.SysUserService;
import com.ipay.utils.Constant;
import com.ipay.utils.HttpUtils;
import com.ipay.utils.PageUtils;
import com.ipay.utils.Query;
import com.ipay.utils.R;
import com.ipay.utils.RandomStringUtils;
import com.ipay.utils.StringUtil;
import com.ipay.utils.Utils;
import com.ipay.utils.ZipUtil;
import com.ipay.validator.ValidatorUtils;
import com.ipay.validator.group.AddGroup;


/**
 * 商户资料
 *
 * @author hacken
 * @email hacken_hu@163.com
 * @date 2017-06-10 15:46:50
 */
@RestController
@RequestMapping("/merchantinfo")
public class MerchantInfoController extends AbstractController {
    private Logger logger = LoggerFactory.getLogger(getClass());
    @Autowired
    private MerchantInfoService merchantInfoService;
    @Autowired
    ServletContext servletContext;
    @Autowired
    private SysUserService userService;
    @Autowired
    private QRCodeService qrCodeService;
    @Autowired
    private CashiersService cashiersService;
    @Autowired
    private JedisConnectionPool pool;

    /**
     * 列表
     */
    @RequestMapping("/list")
    @RequiresPermissions("merchantinfo:list")
    public R list(@RequestParam Map<String, Object> params, HttpServletRequest request) {
        logger.info("params==" + params.toString());
        
        //用户类型 1、后台用户 2、商户
        String userType = getUser().getUserType();

        if ("2".equals(userType)) {  //商户
            String merchantId = (String) request.getSession().getAttribute("merchantId");
            params.put("merchantId", merchantId);
        }
        params.put("deleteStatus", Constant.DELETE_STATUS_NO);
        // 查询列表数据
        Query query = new Query(params);
        logger.info("query==" + query.toString());

        List<MerchantInfoEntity> merchantInfoList = merchantInfoService.queryList(query);
        int total = merchantInfoService.queryTotal(query);
        logger.info("total==" + total);

        PageUtils pageUtil = new PageUtils(merchantInfoList, total, query.getLimit(), query.getPage());

        return R.ok().put("page", pageUtil);
    }

    /**
     * 信息
     *
     * @throws IOException
     */
    @RequestMapping("/info/{id}")
    @RequiresPermissions("merchantinfo:info")
    public R info(@PathVariable("id") Long id, HttpServletRequest request, HttpServletResponse response) throws IOException {
        MerchantInfoEntity merchantInfo = merchantInfoService.queryObject(id);
        merchantInfo.setPositiveImg(pool.getDomainurlManagerHttp() + "merchantinfo/lookImage?filePath=" + merchantInfo.getPositiveImg() + "&imgSize=300x200");
        merchantInfo.setOppositeImg(pool.getDomainurlManagerHttp() + "merchantinfo/lookImage?filePath=" + merchantInfo.getOppositeImg() + "&imgSize=300x200");
        merchantInfo.setInnerImg(pool.getDomainurlManagerHttp() + "merchantinfo/lookImage?filePath=" + merchantInfo.getInnerImg() + "&imgSize=300x200");
        merchantInfo.setOuterImg(pool.getDomainurlManagerHttp() + "merchantinfo/lookImage?filePath=" + merchantInfo.getOuterImg() + "&imgSize=300x200");
        merchantInfo.setLogo(pool.getDomainurlManagerHttp() + "merchantinfo/lookImage?filePath=" + merchantInfo.getLogo() + "&imgSize=400x100");
        merchantInfo.setDoorHeadImg(pool.getDomainurlManagerHttp() + "merchantinfo/lookImage?filePath=" + merchantInfo.getDoorHeadImg() + "&imgSize=300x200");
        merchantInfo.setBusinessLicenseImg(pool.getDomainurlManagerHttp() + "merchantinfo/lookImage?filePath=" + merchantInfo.getBusinessLicenseImg() + "&imgSize=300x200");
        merchantInfo.setBankLicenseImg(pool.getDomainurlManagerHttp() + "merchantinfo/lookImage?filePath=" + merchantInfo.getBankLicenseImg() + "&imgSize=300x200");
        merchantInfo.setSettlementBookImg(pool.getDomainurlManagerHttp() + "merchantinfo/lookImage?filePath=" + merchantInfo.getSettlementBookImg() + "&imgSize=300x200");
        merchantInfo.setSettleUserPositiveImg(pool.getDomainurlManagerHttp() + "merchantinfo/lookImage?filePath=" + merchantInfo.getSettleUserPositiveImg() + "&imgSize=300x200");
        merchantInfo.setSettleUserOppositeImg(pool.getDomainurlManagerHttp() + "merchantinfo/lookImage?filePath=" + merchantInfo.getSettleUserOppositeImg() + "&imgSize=300x200");
        merchantInfo.setSettleBankPositiveImg(pool.getDomainurlManagerHttp() + "merchantinfo/lookImage?filePath=" + merchantInfo.getSettleBankPositiveImg() + "&imgSize=300x200");
        merchantInfo.setSettleBankOppositeImg(pool.getDomainurlManagerHttp() + "merchantinfo/lookImage?filePath=" + merchantInfo.getSettleBankOppositeImg() + "&imgSize=300x200");
        merchantInfo.setSealCardImg(pool.getDomainurlManagerHttp() + "merchantinfo/lookImage?filePath=" + merchantInfo.getSealCardImg() + "&imgSize=300x200");
        return R.ok().put("merchantInfo", merchantInfo);
    }

    /**
     * 根据手机号码查询是否注册商户或收款员
     *
     * @param mobile   String 手机
     * @param request  HttpServletRequest
     */
    @RequestMapping("/checkMobile")
    @ResponseBody
    public R checkMobile(@RequestBody String mobile, HttpServletRequest request) {

        Map<String, Object> map = new HashMap<String, Object>();
        map.put("deleteStatus", Constant.DELETE_STATUS_NO);
        map.put("activateState", Constant.ActivateState.T_DELETED.getValue());
        map.put("mobile", mobile);
        MerchantInfoEntity info = merchantInfoService.queryInfoByMobile(map);
        if (info != null) {
            return R.error("当前手机号已注册商户,请更换手机号码注册");
        }

        CashiersEntity cash = cashiersService.findCashierByMobile(map);
        if (cash != null) {
            return R.error("当前手机号已注册收款员,请更换手机号码注册");
        }

        return R.ok();
    }

    /**
     * 新增商户
     */
    @RequestMapping("/save")
    @RequiresPermissions("merchantinfo:save")
    public R save(@RequestBody MerchantInfoEntity merchantInfo) {
    	ValidatorUtils.validateEntity(merchantInfo, AddGroup.class);
    	
        merchantInfo.setApplyTime(new Date());
        merchantInfo.setStatus(Constant.IS_VERIFY_NO);
        merchantInfoService.save(merchantInfo);
        return R.ok();
    }

    /**
     * 新增子商户
     */
    @RequestMapping("/saveSonMerchant")
    @RequiresPermissions("merchantinfo:saveSonMerchant")
    public R saveSonMerchant(@RequestBody MerchantInfoEntity merchantInfo) {
        merchantInfo.setApplyTime(new Date());
        merchantInfo.setStatus(Constant.IS_VERIFY_NO);
        merchantInfoService.save(merchantInfo);
        return R.ok();
    }


    /**
     * 修改
     */
    @RequestMapping("/update")
    @RequiresPermissions("merchantinfo:update")
    public R update(@RequestBody MerchantInfoEntity merchantInfo) {
        //merchantInfo.setJoinTime(new Date());
        merchantInfo.setLogo(null);
        merchantInfo.setPositiveImg(null);
        merchantInfo.setOppositeImg(null);
        merchantInfo.setInnerImg(null);
        merchantInfo.setOuterImg(null);
        merchantInfoService.update(merchantInfo);

        return R.ok();
    }

    /**
     * 删除
     */
    @RequestMapping("/delete")
    @RequiresPermissions("merchantinfo:delete")
    public R delete(@RequestBody Long[] ids) {
        merchantInfoService.deleteBatch(ids);
        return R.ok();
    }
    
    /**
     * 冻结
     */
    @RequestMapping("/frozen")
    @RequiresPermissions("merchantinfo:frozen")
    public R frozen(@RequestBody Long[] ids) {
    	if (ids != null && ids.length > 0) {
    		for (int i = 0; i < ids.length; i++){
    			MerchantInfoEntity merchantInfo = merchantInfoService.queryObject(ids[i]);
    			merchantInfo.setStatus(Constant.IS_VERIFY_DJ);//状态冻结
    	        merchantInfoService.update(merchantInfo);
    		}
    	}
    	return R.ok();
    }
    
    /**
     * 解冻
     */
    @RequestMapping("/unFrozen")
    @RequiresPermissions("merchantinfo:unFrozen")
    public R unFrozen(@RequestBody Long[] ids) {
    	if (ids != null && ids.length > 0) {
    		for (int i = 0; i < ids.length; i++){
    			MerchantInfoEntity merchantInfo = merchantInfoService.queryObject(ids[i]);
    			merchantInfo.setStatus(Constant.IS_VERIFY_YES);//状态正常
    	        merchantInfoService.update(merchantInfo);
    		}
    	}
    	return R.ok();
    }

    /**
     * 审核
     */
    @RequestMapping("/review")
    @RequiresPermissions("merchantinfo:review")
    public R review(@RequestBody Long[] ids) {
        if (ids != null && ids.length > 0) {
            for (int i = 0; i < ids.length; i++) {
                MerchantInfoEntity entity = merchantInfoService.queryObject(ids[i]);
                if (StringUtil.isNotEmpty(entity.getStatus()) && entity.getStatus().intValue() == Constant.IS_VERIFY_YES.intValue()) {
                    return R.error("该商户已审核");
                }else if(StringUtil.isNotEmpty(entity.getStatus()) && entity.getStatus().intValue() == Constant.IS_VERIFY_NO.intValue() && entity.getPresentNub() == 3){
                    entity.setJoinTime(new Date());
                    // 审核更改状态 为 正常 （状态码 1 ）
                    entity.setStatus(Constant.IS_VERIFY_YES);
                    Map<String,String> map = merchantInfoService.merchantVerify(entity);
                    String msgId = (String) map.get("msgId");
                    if(!msgId.isEmpty()){
                        merchantInfoService.kafkaProducer();
                        merchantInfoService.produce(msgId);//生产者 生产消息
                    }
                    try {
                        JSONObject result = HttpUtils.getValidCode(entity.getMobilephone(), "49348", map);
                        //JSONObject result = HttpUtils.getValidCode("13755084994", "49348", map);
                        if (result != null && result.getInt("error_code") == 0) { // 发送成功
                            System.out.println("发送短信验证码返回结果：" + result);
                        }
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
                else if(StringUtil.isNotEmpty(entity.getStatus()) && entity.getStatus().intValue() == Constant.IS_VERIFY_NO.intValue() && entity.getPresentNub() != 3){
                    return R.error("该商户处于注册状态，无法审核");
                }else{
                    return R.error("该商户暂时无法审核");
                }
            }
        }
        return R.ok();
    }
    
    

    /**
     * 企业进件资料打包下载
     *
     * @param ""id String 商户编号
     * @param request    HttpServletRequest
     * @throws Exception 
     */
    @RequestMapping("/dataDoZip")
    @RequiresPermissions("merchantinfo:dataDoZip")
    public void dataDoZip(HttpServletRequest request,HttpServletResponse response) throws Exception {
    	String id = request.getParameter("id");
    	MerchantInfoEntity info = merchantInfoService.queryObject(Long.parseLong(id));
    	File [] tarFile = merchantInfoService.creatFile(info);
    	
    	String filePath = Utils.getZipUploadPath(request);
    	//String filePath = Constant.UPLOAD_ZIP_PATH;//上传路径
    	File savefile = new File(filePath);
        if (!savefile.exists()) {// 如果不存在就创建一个
            savefile.mkdirs();
        }
    	
        String zipName = ZipUtil.doZIP(filePath + "/"+info.getMerchantNo()+".zip",tarFile);//这里，我写了一个将多个文件打包为zip的方法doZip()，doZip()返回生成的zip路径

        response.setContentType("application/x-msdownload");
        String fileName = info.getShopName()+"企业进件资料";
        FileInputStream fis=null;
        try {
            fileName = new String(fileName.getBytes("gb2312"), "ISO8859-1");
            response.setHeader("Content-Disposition", "attachment; filename=" + fileName + ".zip");
            ServletOutputStream sos = response.getOutputStream();
            fis = new FileInputStream(zipName);
            int flag = 0;
            byte[] buff = new byte[1024 * 4];
            while ((flag = fis.read(buff, 0, buff.length)) != -1) {
                sos.write(buff, 0, flag);
            }
            fis.close();
            sos.close();
        } catch (IOException e) {
            throw new NullPointerException("下载出现错误！");
        }finally {
            if(fis!=null){
                try {
                    fis.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        /*response.setCharacterEncoding("utf-8");//设置编码统一
        response.setContentType("multipart/form-data");//设置multipart
        //响应头部
        String fileName = info.getShopName()+"进件资料";//
        //response.setHeader("Content-disposition", "attachment;filename=order_" + "进件资料" + ".zip");
        fileName = new String(fileName.getBytes("gb2312"), "ISO8859-1");
        response.setHeader("Content-Disposition", "attachment; filename=" + fileName + ".zip");
        InputStream inputStreamzip = new FileInputStream(new File(zipName));//通过zip路径实例化inputStream流

        OutputStream os = response.getOutputStream();
        byte[] b = new byte[2048];
        int length;
        while ((length = inputStreamzip.read(b)) > 0) {
            os.write(b, 0, length);
        }
        os.close();
        inputStreamzip.close();*/
        
    }

    /**
     * 查看二维码
     *
     * @param codeNo   String 收款码编号
     * @param request  HttpServletRequest
     * @param response HttpServletResponse
     */
    @RequestMapping("/lookqrCode")
    public void lookqrCode(@RequestParam String codeNo, HttpServletRequest request, HttpServletResponse response) {
        QRCodeEntity qRCode = qrCodeService.findCodeDetailsByCodeno(codeNo);
        if (qRCode != null) {
            String url = pool.getBaseUrl() + qRCode.getUrl() + "&codeNo=" + codeNo;//商户编号  +  收款码编号
            String merchantNo = qRCode.getMerchantId();
            response.setContentType("image/jpeg");
            try {
                com.ipay.core.QRCode.printQRCodeByLogo(response.getOutputStream(), url, codeNo, merchantNo);
            } catch (IOException e) {
                logger.error("查看二维码输出异常：", e);
            }
        }
    }

    /**
     * 查看图片
     *
     * @param filePath String 图片路径
     * @param request  HttpServletRequest
     * @param response HttpServletResponse
     *                 127.0.0.1:8081/merchantinfo/lookImage?filePath=F:\qycache\88888889\593703.jpg
     */
    @RequestMapping("/lookImage")
    public void lookImage(@RequestParam String filePath, HttpServletRequest request, HttpServletResponse response) {
        String imgSize = request.getParameter("imgSize");///图片尺寸大小  100x100
        String realPath = request.getSession().getServletContext().getRealPath("/");
        if(StringUtil.isNotEmpty(filePath) && (!"null".equals(filePath))){
	        if (StringUtil.isNotEmpty(imgSize)) {
	            String retufilePath = new Utils().resize(pool.getUploadImgPath() + filePath, imgSize, realPath);
	            Utils.look(retufilePath, response);
	        } else {
	            ///判断文件是否存在
	            logger.info(pool.getUploadImgPath()  + filePath + "    =====    ");
	            File file = new File(pool.getUploadImgPath()  + filePath);
	            logger.info(pool.getUploadImgPath() + filePath + "    =====    " + (file.exists()));
	            if (file.exists()) {
	                Utils.look(pool.getUploadImgPath()  + filePath, response);
	            } else {
	                ///todo 默认图片处理  带修改
	                String retufilePath = realPath + Constant.DEFAULT_PNG;
	                Utils.look(retufilePath, response);
	            }
	        }
        }else{
        	///todo 默认图片处理  带修改
        	String retufilePath = realPath + Constant.DEFAULT_PNG;
            Utils.look(retufilePath, response);
        }
    }

    /**
     * 查询个人商户二维码列表
     *
     * @param id
     * @param request
     * @return
     */
    @RequestMapping(value = "/getCodeList", method = RequestMethod.GET)
    public ModelAndView getCodeList(String id, HttpServletRequest request) {
        //根据商户id查询 二维码表
        List<QRCodeEntity> list = qrCodeService.getListByMerchantId(id);
        if (list.size() > 0) {
            for (QRCodeEntity code : list) {
                code.setSaveUrl("/merchantinfo/lookqrCode?codeNo=" + code.getCodeNo());
                //code.setSaveUrl("http://localhost:8080/merchantinfo/lookqrCode?codeNo="+code.getCodeNo());
            }
        }
        return new ModelAndView("/merchant/codeList.jsp").addObject("codeList", list);
    }

    @RequestMapping(value = "/fileUpload", method = RequestMethod.POST)
    public R upLoad(HttpServletResponse response, HttpServletRequest request,
                    MultipartFile file) throws IOException {
        String mchId = request.getParameter("id");
        String imginput = request.getParameter("imginput");
        if (file != null && StringUtil.isNotEmpty(mchId) && StringUtil.isNotEmpty(imginput)) {
            String fileName = file.getOriginalFilename();
            logger.info("旧文件名" + fileName);
            fileName = RandomStringUtils.randomNumeric(8) + 
            		fileName.substring(fileName.lastIndexOf("."));
            logger.info("新文件名" + fileName);
            
            MerchantInfoEntity merchantInfo = merchantInfoService.queryObject(Long.valueOf(mchId));
            if (merchantInfo != null && StringUtil.isNotEmpty(merchantInfo.getMerchantNo())) {
                String filePath = pool.getUploadImgPath() + "/" + merchantInfo.getMerchantNo() + "/" + "merchantInfo";
                File tempFile = new File(filePath);
                if (!tempFile.getParentFile().exists()) {
                    try {
                        tempFile.mkdirs();
                    }catch (SecurityException  e){
                        logger.info("创建目录异常：",e);
                    }
                }
                filePath = filePath + "/" + String.valueOf(fileName);
                File tempFile2 = new File(filePath);
                /*if (!tempFile2.exists()) {
                    //tempFile.mkdirs();
                    tempFile2.createNewFile();
                }*/
                file.transferTo(tempFile2);
                filePath = "/" + merchantInfo.getMerchantNo() + "/" + "merchantInfo" + "/" + String.valueOf(fileName);

                if (imginput.equals("positiveImg")) {
                    merchantInfo.setPositiveImg(filePath);
                } else if (imginput.equals("oppositeImg")) {
                    merchantInfo.setOppositeImg(filePath);
                } else if (imginput.equals("innerImg")) {
                    merchantInfo.setInnerImg(filePath);
                } else if (imginput.equals("outerImg")) {
                    merchantInfo.setOuterImg(filePath);
                } else if (imginput.equals("logo")) {
                    merchantInfo.setLogo(filePath);
                } else if (imginput.equals("doorHeadImg")) {
                    merchantInfo.setDoorHeadImg(filePath);
                } else if (imginput.equals("businessLicenseImg")) {
                    merchantInfo.setBusinessLicenseImg(filePath);
                } else if (imginput.equals("bankLicenseImg")) {
                    merchantInfo.setBankLicenseImg(filePath);
                } else if (imginput.equals("settlementBookImg")) {
                    merchantInfo.setSettlementBookImg(filePath);
                } else if (imginput.equals("settleUserPositiveImg")) {
                    merchantInfo.setSettleUserPositiveImg(filePath);
                } else if (imginput.equals("settleUserOppositeImg")) {
                    merchantInfo.setSettleUserOppositeImg(filePath);
                } else if (imginput.equals("settleBankPositiveImg")) {
                    merchantInfo.setSettleBankPositiveImg(filePath);
                } else if (imginput.equals("settleBankOppositeImg")) {
                    merchantInfo.setSettleBankOppositeImg(filePath);
                } else if (imginput.equals("sealCardImg")) {
                    merchantInfo.setSealCardImg(filePath);
                }
                boolean flag = checkPresentNub(merchantInfo);
                if(flag){
                	merchantInfo.setPresentNub(3);
                }
                merchantInfoService.update(merchantInfo);
            }
        }
        return R.ok();
    }
    
    /**
     * 
     * @param merchantInfo
     * @return
     */
    public boolean checkPresentNub(MerchantInfoEntity merchantInfo){
    	//先判断身份证正反面、营业执照、 银行开户许可证、门店照片是否为空
    	if(StringUtil.isNotEmpty(merchantInfo.getPositiveImg()) 
    			&& StringUtil.isNotEmpty(merchantInfo.getOppositeImg()) 
    				&& StringUtil.isNotEmpty(merchantInfo.getBankLicenseImg())  
    					&& StringUtil.isNotEmpty(merchantInfo.getOuterImg()) 
    						&& StringUtil.isNotEmpty(merchantInfo.getBusinessLicenseImg())   ){
    		//再判断结算账户申请书或印鉴卡是否为空 或者 结算授权书、结算人身份证正面、结算人银行卡正反面是否为空
    		if(StringUtil.isNotEmpty(merchantInfo.getSealCardImg()) || 
    				(StringUtil.isNotEmpty(merchantInfo.getSettlementBookImg()) 
    					&& StringUtil.isNotEmpty(merchantInfo.getSettleUserOppositeImg()) 
    						&& StringUtil.isNotEmpty(merchantInfo.getSettleUserOppositeImg()) 
    							&& StringUtil.isNotEmpty(merchantInfo.getSettleBankOppositeImg()) 
    								&& StringUtil.isNotEmpty(merchantInfo.getSettleBankPositiveImg()) ) ){
    			return true;
    		}
    	}
    	return false;
    }

    /**
     * 商户信息下拉列表
     */
    @RequestMapping("/getMerchantInfoSelect")
    @ResponseBody
    @RequiresPermissions("merchantInfo:list")
    public R getMerchantInfoSelect(HttpServletRequest request, HttpServletResponse response) {
        Map<String, Object> params = new HashMap<String, Object>();
        String userType = getUser().getUserType();
        if (userType != null && userType.equals(Constant.USER_TYPE_SH)) {
            String merchantNo = getUser().getMerchantNo();
            params.put("merchantNo", merchantNo);
        }
        params.put("status", Constant.IS_VERIFY_YES);
        params.put("deleteStatus", Constant.DELETE_STATUS_NO);
        logger.info("params==" + params.toString());
        // 查询列表数据
        List<MerchantInfoEntity> list = merchantInfoService.querySelectByParam(params);
        logger.info("options==" + list);

        return R.ok().put("options", list);
    }
}
